package io.jee.runshan.service.remote.weixin.impl;

import io.jee.medusa.orm.pager.Pager;
import io.jee.medusa.remote.RemoteConnector;
import io.jee.runshan.domain.remote.weixin.WeixinUserInfo;
import io.jee.runshan.domain.remote.weixin.WeixinUserinfoList;
import io.jee.runshan.service.remote.weixin.IUserInfoService;
import io.jee.runshan.utils.WeixinConstant;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class UserInfoServiceImpl implements IUserInfoService {
	private static final String getWeixinUserInfoAction = "user/info";
	private static final String getWeixinUserInfoListAction = "user/get";

	@Override
	public WeixinUserInfo getWeixinUserInfo(String openid) {
		String actionUrl = WeixinConstant.sendUrl(getWeixinUserInfoAction, "openid", openid);
		return RemoteConnector.post(actionUrl, null, WeixinUserInfo.class);
	}

	@Override
	public Pager<WeixinUserInfo> getWeixinUserinfoList(Pager<WeixinUserInfo> pager) {
		List<WeixinUserInfo> result = null;
		String actionUrl = WeixinConstant.sendUrl(getWeixinUserInfoListAction);
		WeixinUserinfoList list = RemoteConnector.post(actionUrl, null, WeixinUserinfoList.class);
		if (list != null && list.getTotal() > 0) {
			result = new ArrayList<WeixinUserInfo>();
			int total = list.getTotal();
			int start = (pager.getPagenum() - 1) * pager.getPagesize();
			int end = start + pager.getPagesize();
			if (end > total) end = total;
			for (int i = start; i < end; i++) {
				result.add(getWeixinUserInfo(list.getData().getOpenid()[i]));
			}
			pager.setDatas(result);
		}
		return pager;
	}

}
